package com.monitor.commons.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.monitor.commons.StringUtil;
import com.monitor.pubInter.BaseIdDoMain;
import com.monitor.pubInter.IBaseService;
import com.monitor.pubInter.exception.SkException;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;


import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class PageReadListener<T> implements ReadListener<T> {
    //    每隔100条存数据库
    public static int BATCH_COUNT = 100;
//    临时数据
    private List<T> cachedDataList;
    @Autowired
    private IBaseService baseService;
    @Resource(name = "skDozerMapper")
    private Mapper mapper;

    private Class<T> destinationClass;


    public PageReadListener(IBaseService baseService, Class<T> destinationClass) {
        this(baseService,destinationClass,BATCH_COUNT);
    }

    public PageReadListener(IBaseService baseService, Class<T> destinationClass, int batchCount) {
        this.cachedDataList= ListUtils.newArrayListWithExpectedSize(batchCount);
        this.baseService = baseService;
        this.destinationClass=destinationClass;
    }


    @Override
    public void invoke(T t, AnalysisContext analysisContext) {
        cachedDataList.add(t);
        if(cachedDataList.size()>=BATCH_COUNT){
            saveData();
        }
    }

    /**
     * 每解析完一页sheet 就会调用该方法
     * @param analysisContext
     */
    @SneakyThrows
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        log.info("读取当前文件第【"+(analysisContext.readSheetHolder().getSheetNo() + 1)+"】sheet页");
        if(cachedDataList.size()>0){
            saveData();
        }
    }
    private void saveData(){
        try {
            if(StringUtil.isNotObjEmpty(cachedDataList) && !cachedDataList.isEmpty()){
//                批量插入
                baseService.batchInsert(cachedDataList);
//                插入完成后清理
                cachedDataList=new ArrayList<>();
            }

        } catch (SkException e) {
            throw new RuntimeException(e);
        }
    }
}
